__auth__ = "miao.zhifeng<19195659@qq.com>"
__doc__ = """ 
使用二分法设计平方根求解x
在1-x中间使用二分法查找
"""

def SquareRoot(x,eps):
	if x < 0 or eps <= 0:return -1
	max_cnt = 100
	
	cnt = 1
	low = 0
	high = max(x,1.0)
	guess = (low+high)/2

	while abs(guess**2-x) > eps and cnt<=max_cnt:
		if guess**2 < x:
			low = guess
		else:
			high = guess
		guess = (low + high) / 2
		cnt += 1
	return cnt,guess
cnt,value = SquareRoot(0.25,0.0001)

print("iteration的次数{0},平方根是{1}".format(cnt,value))

def SquareRootB2(x,eps):
	if x<0 or eps<=0: return -1
	x = float(x)
	guess = x/2
	diff = guess**2-x
	cnt = 1

	while abs(diff) > eps and cnt<=100:
		guess = guess-diff/(2.0*guess)
		diff = guess**2 - x
		cnt += 1
	return cnt, guess
cnt,value = SquareRootB2(0.25,0.0001)
print("iteration的次数{0},平方根是{1}".format(cnt,value))
